<template>
	<div class="">
		<div ref="amapRef" class="w-full h-full"></div>
		<div ref="MarkerLabelRef">
			<MarkerLabel :site-data="siteData" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { fetchListByTag as fetchList } from '/@/api/platform/airMonitorEquipment';
import { useScript } from '/@/hooks/web/useScript';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { fetchByEquipmentId } from '/@/api/platform/airRealTimeData';
import { handleTree } from '/@/utils/other';
import { useMessage } from '/@/hooks/message';
import MapDevIcon_0 from '/@/assets/markers/map-DEV-0.png'; //掉线图标
import MapDevIcon_1 from '/@/assets/markers/map-DEV-1.png'; //在线图标
import MapDevIcon_2 from '/@/assets/markers/map-DEV-2.png'; //警报图标
import MarkerLabel from './markerLabel.vue';

const A_MAP_URL = 'https://webapi.amap.com/maps?v=1.4.15&key=24a6afd6ab0b81c1bda89e736ff24c6f&plugin=AMap.MarkerClusterer';
const amapRef = ref();
const { toPromise } = useScript({ src: A_MAP_URL });
const pageData: any = ref([]);
const siteData = reactive({});
const MarkerLabelRef = ref();
const tag = ref();
let map: any;
let AMap: any;
let _MarkerCluster: any;
let infoLayer: any;
async function initMap() {
	await toPromise();
	await nextTick();
	const wrapEl = unref(amapRef);
	if (!wrapEl) return;
	AMap = (window as any).AMap;
	map = new AMap.Map(wrapEl, {
		resizeEnable: true,
		animateEnable: true,
		center: [107.604208, 31.51514],
		zoom: 4,
		mapStyle: 'amap://styles/blue',
	});
	infoLayer = new AMap.InfoWindow({
		isCustom: true, //使用自定义窗体
		closeWhenClickMap: true,
		offset: new AMap.Pixel(8, -30),
		anchor: 'bottom-center',
	});
	const points: any = [];
	const markers: any = [];
	for (let i = 0; i < pageData.value?.length; i++) {
		const item = pageData.value[i];
		const p = {
			lnglat: [item.longitude, item.latitude],
			url: item.status === 2 ? (item.alarmStatus === 2 ? MapDevIcon_2 : MapDevIcon_1) : MapDevIcon_0,
			name: item.name,
			status: item.status === 2 ? (item.alarmStatus === 2 ? '警报' : '在线') : '掉线',
			class: item.status === 2 ? (item.alarmStatus === 2 ? 'text-error' : 'text-success') : 'text-info',
			id: item.id,
		};
		points.push(p);
		const content = `<div><span class="mr-1">${p.name}</span><span class="${p.class}">${p.status}</span></div>`;

		const marker = new AMap.Marker({
			icon: new AMap.Icon({
				size: new AMap.Size(30, 38),
				image: p.url,
			}),
			position: new AMap.LngLat(item.longitude, item.latitude),
			offset: new AMap.Pixel(-15, -15),
			label: {
				content,
				direction: 'top',
			},
		});
		marker.extrm;
		marker.on('click', async () => {
			try {
				const res = await fetchByEquipmentId({ monitorEquipmentId: item.id });
				Object.assign(siteData, res.data, { equipmentName: p.name, status: item.status });
				const content = unref(MarkerLabelRef);
				infoLayer.setContent(content);
				infoLayer.open(map, marker.getPosition());
				map.setCenter(marker.getPosition());
			} catch (err: any) {
				useMessage().error(err.msg);
			}
		});
		markers.push(marker);
	}
	nextTick(() => {
		_MarkerCluster = new AMap.MarkerClusterer(map, markers, {
			clusterByZoomChange: true,
			gridSize: 80,
		});
		_MarkerCluster.on('click', (item: any) => {
			//此处是通过包含点的数量判断是否是聚合点
			if (item.markers.length <= 1) {
				return;
			}
			var curZoom = map.getZoom();
			if (curZoom < 20) {
				curZoom += 1;
			}
			map.setZoomAndCenter(curZoom, item.lnglat);
		});
		// new AMap.Polygon({
		// 	path: points, //以5个点的坐标创建一个隐藏的多边形
		// 	map: map,
		// 	strokeOpacity: 0, //透明
		// 	fillOpacity: 0, //透明
		// 	bubble: true, //事件穿透到地图
		// });
		// const overlaysList = map.getAllOverlays('polygon'); //获取多边形图层
		// map.setFitView(overlaysList);
		// map.setFitView(markers);
	});
}
const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			const l = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			tag.value = l[0]?.id;
			getDataList();
		}
	});
};
const getDataList = () => {
	fetchList({ tag: tag.value }).then((res) => {
		pageData.value = res.data;
		if (!map) {
			initMap();
		}
	});
};
onMounted(() => {
	getTreeDate();
});
</script>

<style lang="scss" scoped>
:deep(.amap-marker-label) {
	color: #fff;
	background-color: #074e6e;
	border: 1px solid #074e6e;
	box-shadow: 0px 12px 32px 4px rgba(7, 78, 110, 0.6), 0px 8px 20px rgba(7, 78, 110, 0.6);
	border-radius: 12px;
}
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
</style>
